package middleware

import (
	"SSO/config"
	"SSO/controllers"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type SSO struct {}

func (SSO) Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		controller := controllers.Controller{}
		username := controller.SessionGet("username", c)
		if username != nil {
			c.Next()
		} else {
			c.Abort()
			conf := config.GetConf().Base
			callbackUrl := c.DefaultQuery("callback_url", "")
			if callbackUrl == "" {
				callbackUrl = fmt.Sprintf("%s%s", conf.Domain, c.Request.RequestURI)
			}

			urlStr := fmt.Sprintf("%s?callback_url=%s", conf.LoginUrl, callbackUrl)
			c.Redirect(http.StatusFound, urlStr)
		}
	}
}